package com.yst.shader.feature.widget

import android.animation.ValueAnimator
import android.animation.ValueAnimator.INFINITE
import android.animation.ValueAnimator.RESTART
import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.widget.ImageView
import com.yst.shader.R

/**
 * @author: xuyujian@ysten.com
 *  @date: 2020/8/15 19:55
 */
class ShadeView : ImageView {
    constructor(context: Context?) : super(context)
    constructor(context: Context?, attrs: AttributeSet?) : super(context, attrs)

    private val source by lazy { BitmapFactory.decodeResource(resources, R.drawable.test2) }
    private val focus by lazy { BitmapFactory.decodeResource(resources, R.drawable.focus_red) }
    private val paint by lazy {
        Paint(Paint.ANTI_ALIAS_FLAG).apply {
        }
    }


    private val rect by lazy { RectF(0f, 0f, width.toFloat(), height.toFloat()) }
    private val linearGradient by lazy {
        LinearGradient(
            0f, 0f,
            30f, 0f,
            intArrayOf(Color.TRANSPARENT, Color.parseColor("#4cffffff"), Color.TRANSPARENT),
            floatArrayOf(0f, 0.5f, 1f),
            Shader.TileMode.CLAMP
        )
    }

    private var dy = 0f
    private val animator by lazy {
        ValueAnimator.ofFloat(0f, width.toFloat())
            .apply {
                repeatMode = RESTART
                repeatCount = INFINITE
                startDelay = 300
                duration = 3000
                addUpdateListener {
                    dy = it.animatedValue as Float
                    postInvalidate()
                }
            }

    }
    private val localMatrix = Matrix()

    init {
        post {
            animator.start()
        }
    }

    private val centerRect = Rect()

    override fun onDraw(canvas: Canvas) {
        canvas.drawBitmap(focus, null, Rect(0, 0, width, height), paint)
        val saveLayer1 = canvas.saveLayer(rect, paint, Canvas.ALL_SAVE_FLAG)


        canvas.drawBitmap(source, null, Rect(60, 100, 440, 300), paint)
        // canvas.restoreToCount(saveLayer1)
        val alphaW = 200f
        paint.shader = linearGradient
        canvas.matrix = localMatrix
        localMatrix.setTranslate(dy, 0f)
        localMatrix.postRotate(45f, width / 2f, height / 2f)
       // paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)
        canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), paint)
        paint.xfermode = null
        paint.shader = null
        canvas.matrix = null
        paint.color = Color.WHITE
        canvas.drawText("hello" , 220f,250f,paint)
        canvas.restoreToCount(saveLayer1)
//        paint.xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_ATOP)

        canvas.drawText("world" , 250f,250f,paint)

//        canvas.restoreToCount(saveLayer2)
        paint.xfermode = null
    }
}